<?php

namespace app\service;

use app\common\BaseService;
use app\model\Auth as AuthModel;
use app\model\Role as RoleModel;
use app\model\AuthRole as AuthRoleModel;
use think\facade\Db;

class RoleService extends BaseService
{
  public static function getInstance(): RoleService
  {
    return parent::getInstance();
  }

  public static function getModel(): RoleModel
  {
    return RoleModel::getInstance();
  }

  public static function getAuthModel(): AuthModel
  {
    return AuthModel::getInstance();
  }

  public static function getAuthRoleModel(): AuthRoleModel
  {
    return AuthRoleModel::getInstance();
  }

  /*
   * 通过condition获取Role
   */
  public function getRoleByCondition($conditions, $order = ['id' => 'desc']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }

  /*
   * 通过condition获取Auth
   */
  public function getAuthByCondition($conditions, $order = ['id' => 'desc']) {
    $query = self::getAuthModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }

  /*
   * 获取用户所有权限
   */
  public static function getAuthByRole($conditions = [], $order= ['ar.id' => 'desc']) {
    $conditions[] = ['a.status', 1, '='];
    $conditions[] = ['ar.status', 1, '='];
    $query = Db::name('auth_role')
      ->alias('ar')
      ->field('ar.*, a.authname')
      ->join('auth a', 'a.id = ar.auth_id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }


}
